<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center>
        <template #default>
          <van-image
            round
            class="avatar"
            :src="$store.state.headImgUrl"
            @click="imgUploadFn"
          />
          <!-- file 选择框 -->
          <input
            type="file"
            ref="iptFile"
            v-show="false"
            accept="image/*"
            @change="onFileChange"
          />
        </template>
      </van-cell>
      <van-cell
        title="名称"
        is-link
        :value="$store.state.userName"
        @click="dialogFn"
      />
      <van-cell
        title="生日"
        is-link
        :value="userProfileObj.birthday"
        @click="birthdayDateFn"
      />
    </van-cell-group>
    <!-- 弹出编辑名称 -->
    <van-dialog
      v-model="show"
      title="名称"
      show-cancel-button
      :before-close="beforeCloseFn"
    >
      <input type="text" v-fofo v-model="userName" />
    </van-dialog>

    <!-- 时间选择器 -->
    <van-popup v-model="isShow" position="bottom" :style="{ height: '50%' }">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="birthdayConfirmFn"
      />
    </van-popup>
  </div>
</template>

<script>
import { Notify } from 'vant'
import dayjs from 'dayjs'
import { userProfileAPI, uploadHeadImgAPI, uploadUserInfoAPI } from '@/api'
import { mapMutations } from 'vuex'
export default {
  name: 'UserEdit',
  async created () {
    const res = await userProfileAPI()
    // console.log(res)
    this.userProfileObj = res.data.data
    this.setHeadImgUrlMutations(this.userProfileObj.photo)
    this.setUserNameMutations(this.userProfileObj.name)
  },
  data () {
    return {
      userProfileObj: {}, // 用户信息
      show: false, // 修改名称弹框是否显示
      userName: '', // 用户名称
      isShow: false, // 时间选择器是否显示
      minDate: new Date(1921, 0, 1),
      maxDate: new Date(),
      currentDate: new Date()
    }
  },
  methods: {
    ...mapMutations(['setHeadImgUrlMutations', 'setUserNameMutations']),

    // 图片点击事件
    imgUploadFn () {
      this.$refs.iptFile.click()
    },
    // 选择文件 同时 发送图片问价给后台更新头像
    async onFileChange (ev) {
      // console.log(ev.target.files[0])
      //  input[type=file]选择不同的文件->触发change事件
      // 如果已有，变成不选的->触发change事件

      if (ev.target.files.length !== 0) {
        // 参数要传文件, 自己创建fromData对象
        const fromData = new FormData()
        // 加入参数名和值
        fromData.append('photo', ev.target.files[0])
        const res = await uploadHeadImgAPI(fromData)
        // console.log(res)
        this.userProfileObj.photo = res.data.data.photo
        this.setHeadImgUrlMutations(this.userProfileObj.photo)
      }
    },
    // 弹框的显示
    dialogFn () {
      this.show = true
      this.userName = this.userProfileObj.name
    },
    // 修改名称,阻止点击确定时,先判断是否通过校验
    async beforeCloseFn (action, done) {
      // console.log(action)
      if (action === 'cancel') {
        // 取消 -- 关闭弹窗
        done()
      } else {
        if (/^[A-Za-z\u4e00-\u9fa5]{1,7}$/.test(this.userName)) {
          await uploadUserInfoAPI({
            name: this.userName
          })
          this.userProfileObj.name = this.userName
          this.setUserNameMutations(this.userProfileObj.name)
          done()
        } else {
          // 警告通知
          done(false)
          Notify({ type: 'warning', message: '请输入1-7位字母或汉字' })
        }
      }
    },
    // 点击弹出选择时间
    birthdayDateFn () {
      this.isShow = true
      // 修改默认日期
      // (重要):组件要的都是日期对象,后台要的和返回的都是日期字符串(年-月-日)
      this.currentDate = new Date(this.userProfileObj.birthday)
    },
    // 修改时间,点击完成
    async birthdayConfirmFn () {
      // 日期对象转换成日期字符串
      await uploadUserInfoAPI({
        birthday: dayjs(this.currentDate).format('YYYY-MM-DD')
        // this.currentDate.toLocaleDateString()
      })
      // 关闭弹窗
      this.isShow = false
      // console.log(this.currentDate.toLocaleDateString())
      // 同步修改前端单元格内容
      this.userProfileObj.birthday = dayjs(this.currentDate).format(
        'YYYY-MM-DD'
      )
    }
  }
}
</script>

<style lang="less" scoped>
.user-edit-container {
  padding-top: 46px;
  .avatar {
    width: 50px;
    height: 50px;
  }
  /deep/ .van-dialog__content {
    text-align: center;
    input {
      text-align: center;
      border-radius: 10px;
      border: 1px solid #007bff;
    }
  }
}
</style>
